<?php
/**
 * 用户管理
 * 
 * @author  Lee<a605333742@gmail.com>
 * @time    2016-08-09
 */
namespace Admin\Controller; 

class UserController extends CommonController{
    /*
     * 构造函数
     * 
     * @return #
     */
    public function _initialize() {
        parent::_initialize();
        $this->db_role  =D("Role");
        $this->db_user  =D("User");
        $this->db_u_r   =D("UserRole");
    }
    
    /*
     * show前置操作
     * 
     * @return #
     */
    public function _before_show(){
        A("Notice")->_before_show();
        $roleList   =$this->db_role->where(array("status"=>array("neq",0)))->select();
        if(I("request.id")){
            $u_role =$this->db_u_r->where(array("u_id"=>I("request.id")))->getField("role_id");
        }
        $this->assign("u_role",$u_role);
        $this->assign("rlist",$roleList);
    }
    
    /*
     * edit前置操作
     * 
     * @return  #
     */
    public function _before_edit(){
        $map['role_id'] =I("request.role_id");
        if(I("request.id")){
            $map['u_id']=I("request.id");
            if(($this->db_u_r->where(array("u_id"=>I("request.id")))->getField("role_id")) &&($this->db_u_r->where(array("u_id"=>I("request.id")))->getField("role_id")!=$map['role_id'])){
                //如果查询出来的role_id和传过来的role_id不同，则说明有修改过角色                
                $this->db_u_r->where(array("u_id"=>I("request.id")))->save($map);                
            }else if(!$this->db_u_r->where(array("u_id"=>I("request.id")))->getField("role_id")){
                 $this->db_u_r->add($map);
            }
            if(I("request.newPassword")){
                $_POST['password']  =md5(trim(I("request.newPassword")));
            }
        }else{
            $map['u_id']=($this->db_user->max('id'))+1;
            $this->db_u_r->add($map);
            $_POST['password']  =md5(trim(I("request.newPassword")));
        }
    }
    
    /*
     * 删除用户前置操作
     * 
     * @return @
     */
    public function _before_del(){
        $del_id =I("request.id");
        if(!is_array($del_id)){
            $del_id =explode(",",code($del_id));
        }
        if(in_array("1",$del_id) || in_array(session("authId"),$del_id)){
            $this->error("不能删除超级管理员或者自己");
            exit;
        }
    }
}